# 寻找两个有序数组的中位数

# 时间复杂度要求为O(log (m+n))，若是用合并排序数组的方法来做的话，时间复杂度应该为O(m+n)

# 需要一个递归函数，每次能减少一半的查询规模。设K=(m+n)/2

# nums1 = [1, 3] nums2 = [2] -> 2.0
# nums1 = [1, 2] nums2 = [3, 4] -> 2.5

# 分析详见：
# zhuanlan.zhihu.com/p/39129143

nums1 = [1, 3]
nums2 = [2]

nums3 = [1, 2]
nums4 = [3, 4]

def median(A, B):
    m, n = len(A), len(B)
    if m > n:
        A, B, m, n = B, A, n, m
    if n == 0:
        raise ValueError

    imin, imax, half_len = 0, m, (m + n + 1) / 2
    while imin <= imax:
        i = int((imin + imax) / 2)
        j = int(half_len - i)
        if i < m and B[j-1] > A[i]:
            # i is too small, must increase it
            imin = i + 1
        elif i > 0 and A[i-1] > B[j]:
            # i is too big, must decrease it
            imax = i - 1
        else:
            # i is perfect

            if i == 0: max_of_left = B[j-1]
            elif j == 0: max_of_left = A[i-1]
            else: max_of_left = max(A[i-1], B[j-1])

            if (m + n) % 2 == 1:
                return max_of_left

            if i == m: min_of_right = B[j]
            elif j == n: min_of_right = A[i]
            else: min_of_right = min(A[i], B[j])

            return (max_of_left + min_of_right) / 2.0

print(median(nums1, nums2))
print(median(nums3, nums4))

# 对比A数组和B数组的第K/2个元素，谁小就把那个数组的前K//2个数直接砍了。递归执行。

# def median(A, B):
#     def findMedianSortedArrays(A, B):
#         n = len(A) + len(B)
#         if n % 2 == 1:
#             return findKth(A, B, n / 2 + 1)
#         else:
#             smaller = findKth(A, B, n / 2)
#             bigger = findKth(A, B, n / 2 + 1)
#             return (smaller + bigger) / 2.0

#     def findKth(A, B, k):
#         if len(A) == 0:
#             return B[int(k - 1)]
#         if len(B) == 0:
#             return A[int(k - 1)]
#         if k == 1:
#             return min(A[0], B[0])

#         a = A[int(k / 2) - 1] if len(A) >= k / 2 else None
#         b = B[int(k / 2) - 1] if len(B) >= k / 2 else None

#         if b is None or (a is not None and a < b):
#             return findKth(A[int(k / 2):], B, int(k - k // 2))
#         return findKth(A, B[int(k / 2):], int(k - k // 2))
